package com.rockcent.service;

import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.helper.OrderEventHelper;
import com.rockcent.mall.lib.helper.OrderStatusHelper;
import com.rockcent.mall.lib.helper.ProductEventHelper;
import com.rockcent.mall.lib.helper.VerificationHelper;
import com.rockcent.mall.lib.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by oyhk on 2017/1/15.
 */
@Service
public class PaymentService {

    private final Logger log = LoggerFactory.getLogger(PaymentService.class);
    @Autowired
    private MerchantOrderRepository merchantOrderRepository;
    @Autowired
    private MarketOrderRepository marketOrderRepository;
    @Autowired
    private FundService fundService;
    @Autowired
    private MerchantOrderItemRepository merchantOrderItemRepository;
    @Autowired
    private OrderEventHelper orderEventHelper;
    @Autowired
    private MerchantGiftPacketCouponRepository merchantGiftPacketCouponRepository;
    @Autowired
    private CustomerCouponWalletRepository customerCouponWalletRepository;
    @Autowired
    private ProductEventHelper productEventHelper;
    @Autowired
    private MerchantCouponRepository merchantCouponRepository;
    @Autowired
    private VerificationHelper verificationHelper;
    @Autowired
    private MerchantOrderVerificationRepository merchantOrderVerificationRepository;

    /**
     * 支付成功修改商家订单
     * @param merchantOrderList
     */
    public void modifyMerchantOrder(MallOrder mallOrder ,List<MerchantOrder> merchantOrderList) {
        OrderStatusHelper.SINGLETON.merchantOrderPayed(merchantOrderList); // 修改商家订单为已支付

        Date datePayment = new Date();
        merchantOrderList.forEach(merchantOrder -> {
            merchantOrder.setPaymentMethod(mallOrder.getPaymentMethod());
            merchantOrder.setDatePayment(datePayment);
            merchantOrderRepository.save(merchantOrder);
            // 订单事件
            orderEventHelper.saveOrderEvent(merchantOrder, OrderEventType.PAYED, mallOrder.getCustomerName(), mallOrder.getCustomerId());
            //product_event记录相应事件
            List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(merchantOrder.getId(), merchantOrder.getMerchantId());
            merchantOrderItemList.forEach(merchantOrderItem -> {
                productEventHelper.productEventSave(merchantOrder, merchantOrderItem, merchantOrderItem.getBuyCount(), ProductEventType.SALED);
            });
        });

        // 分销订单
        List<MerchantOrder> marketMerchantOrderList = merchantOrderList.stream().filter(merchantOrder -> merchantOrder.getSourceType() == MerchantOrderSourceType.MARKET && merchantOrder.getMerchantRole() == MerchantOrderMerchantRole.DISTRIBUTOR).collect(Collectors.toList());
        marketMerchantOrderList.forEach(merchantOrder -> {
            MarketOrder marketOrder = marketOrderRepository.findByOrderNum(merchantOrder.getMarketOrderNum());
            OrderStatusHelper.SINGLETON.marketOrderPayed(marketOrder, merchantOrder);
            marketOrder.setPaymentMethod(mallOrder.getPaymentMethod());
            marketOrder.setDatePayment(datePayment);
            marketOrderRepository.save(marketOrder);

            //product_event记录相应事件
            List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(merchantOrder.getId(), merchantOrder.getMerchantId());
            merchantOrderItemList.forEach(merchantOrderItem -> {
                productEventHelper.productEventSave(merchantOrder, merchantOrderItem, merchantOrderItem.getBuyCount(), ProductEventType.SALED);
            });
        });
    }

    /**
     * 产品服务结算
     * @param mallOrder
     * @param merchantOrderList
     */
    public void productServiceSettled(MallOrder mallOrder, List<MerchantOrder> merchantOrderList) {

        merchantOrderList.forEach(merchantOrder -> {

            List<MerchantOrderItem> merchantOrderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(merchantOrder.getId(), merchantOrder.getMerchantId());
            if (merchantOrderItemList.size() == 0) {
                log.warn("======================>不可退服务订单异常不能结算");
                return;
            }
            // 礼包中不可退服务，支付成功时，不结算
            if (mallOrder.getGiftId() == null) {
                if (merchantOrder.getOrderType() == OrderType.SERVICE && (merchantOrder.getMerchantRole() == MerchantOrderMerchantRole.SELF || merchantOrder.getMerchantRole() == MerchantOrderMerchantRole.SUPPLIER) && merchantOrderItemList.get(0).getProductRefundable() == Whether.NO) {
                    fundService.serviceVerify(mallOrder, merchantOrder, null, true);


                    MerchantOrderItem merchantOrderItem = merchantOrderItemList.get(0);
                    //记录核销记录
                    MerchantOrderVerification orderVerification = verificationHelper.merchantOrderVerificationSave(merchantOrder, merchantOrderItem, merchantOrderItem.getBuyCount(), null, merchantOrder.getCustomerId(), merchantOrderItem.getLogoUrl(), merchantOrder.getMerchantName(), OrderVerificationWay.SCAN, merchantOrder.getMerchantRole());
                    merchantOrderVerificationRepository.save(orderVerification);
                    //记录分销商核销记录
                    if (merchantOrderItem.getMerchantRole() == MerchantOrderMerchantRole.SUPPLIER) {
                        MerchantOrder marketOrder = merchantOrderRepository.findByMarketOrderNumAndMerchantRole(merchantOrder.getMarketOrderNum(), MerchantOrderMerchantRole.DISTRIBUTOR);
                        List<MerchantOrderItem> orderItemList = merchantOrderItemRepository.findByMerchantOrderIdAndMerchantId(marketOrder.getId(), marketOrder.getMerchantId());
                        MerchantOrderVerification verification = verificationHelper.merchantOrderVerificationSave(marketOrder, orderItemList.get(0), merchantOrderItem.getBuyCount(), null, merchantOrder.getCustomerId(), merchantOrderItem.getLogoUrl(), marketOrder.getMerchantName(), OrderVerificationWay.SCAN, marketOrder.getMerchantRole());
                        merchantOrderVerificationRepository.save(verification);
                    }
                    // 订单事件
                    orderEventHelper.saveOrderEvent(merchantOrder, OrderEventType.VERIFY_CONFIRM, mallOrder.getCustomerName(), mallOrder.getCustomerId());
                }
                //product_event记录相应事件
                merchantOrderItemList.forEach(merchantOrderItem -> {
                    productEventHelper.productEventSave(merchantOrder, merchantOrderItem, merchantOrderItem.getBuyCount(), ProductEventType.VERIFIED);
                });
            }
        });
    }

    /**
     * 礼包赠送卡券
     * @param mallOrder
     */
    public void giftGiveCoupon(MallOrder mallOrder) {
        if (mallOrder.getGiftId() != null) {
            List<MerchantGiftPacketCoupon> merchantGiftPacketCouponList = merchantGiftPacketCouponRepository.findByPacketId(mallOrder.getGiftId());

            merchantGiftPacketCouponList.forEach(merchantGiftPacketCoupon -> {
                CustomerCouponWallet customerCouponWallet = new CustomerCouponWallet();
                customerCouponWallet.setStatus(CustomerCouponWalletStatus.TO_USE);
                customerCouponWallet.setCouponId(merchantGiftPacketCoupon.getCouponId());
                customerCouponWallet.setMallId(mallOrder.getMallId());
                customerCouponWallet.setCustomerId(mallOrder.getCustomerId());
                customerCouponWallet.setSource(CustomerCouponWalletSource.GIFT_PACKET);
                customerCouponWallet.setMerchantId(merchantGiftPacketCoupon.getMerchantId());
                customerCouponWallet.setCustomerName(mallOrder.getCustomerName());
                customerCouponWallet.setGiftId(mallOrder.getGiftId());
                customerCouponWalletRepository.save(customerCouponWallet);

                //卡卷冻结数减-1
                MerchantCoupon merchantCoupon = merchantCouponRepository.findOne(merchantGiftPacketCoupon.getCouponId());
                merchantCoupon.setQuantityFrozen(merchantCoupon.getQuantityFrozen() - 1);
                merchantCoupon.setQuantityUsed(merchantCoupon.getQuantityUsed() + 1);
                merchantCouponRepository.save(merchantCoupon);
            });

        }
    }


}
